package com.peng.leetcode.array;

/**
 * FindMaxAverage
 * <p>
 * 643. 子数组最大平均数 I
 *
 * @author: lupeng6
 * @create: 2021/2/4 12:04
 */
public class FindMaxAverage {

    public static void main(String[] args) {
        int[] nums = {1, 12, -5, -6, 50, 3};
        int k = 4;
        System.out.println(new FindMaxAverage().findMaxAverage(nums, k));
    }

    public double findMaxAverage(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int sum = 0;
        double avg = 0;
        for (int i = 0; i < k; i++) {
            sum += nums[i];
        }
        avg = (double) sum / k;

        for (int i = k; i < nums.length; i++) {
            int add = nums[i];
            int delete = nums[i - k];
            sum += add;
            sum -= delete;
            double tempAvg = (double) sum / k;
            avg = Math.max(tempAvg, avg);
        }

        return avg;
    }
}
